package edu.ccut.saturn.studio.core.util.eclipse;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.core.exception.XMLException;
import edu.ccut.saturn.studio.core.saturnproperty.StringUtils;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;

/**
 * @author 郭英杰
 * @author 杨艳斌
 * 
 * @version 1.1 2009.11.23
 */
public class SaturnProjectUtil {
	
	private static final String SEPARATOR = File.separator;
	private static final String FILECLASSPATH = ".classpath";
	private static final String CLASSPATH_NODE_NAME = "classpathentry";
	private static final String SATURN_FOLDER_DESCRIPTION = "description";
	private static final String CLASSPATH_ATTRIBUTE_KIND = "kind";
	private static final String CLASSPATH_ATTRIBUTE_PATH = "path";
	private static final String TYPE_FILE_NAME = ".saturn";
	private static final String SATURN_FOLDER_TYPE = "type";
	private static final String SATURN_COMPONENT_COMPONENT = "component";
	private static final String SATURN_COMPONENT_LOGIC = "logic";
	private static final String SATURN_COMPONENT_ACTION = "action";
	private static final String SATURN_COMPONENT_WORKFLOW = "workflow";
	private static final String SATURN_COMPONENT_WF = ".wf";
	private static final String SATURN_COMPONENT_SATURNDATA = ".saturndata";
	private static final String SATURN_COMPONENT_VALIDATE = "validate";
	private static final String SATURN_COMPONENT_WEB = "web";
	private static final String SATURN_COMPONENT_JSP = ".jsp";
	private static final String SATURN_COMPONENT_DATA = "data";
	
	
	public static IProject[] getAllProjects() {
		return ResourcesPlugin.getWorkspace().getRoot().getProjects();
	}
	
	public static IResource getResource(IStructuredSelection selection) {
		IStructuredSelection structureSele = new StructuredSelection(
				IDE.computeSelectedResources(selection));

		return (IResource) structureSele.getFirstElement();
	}
	
	public static IProject getProject(IStructuredSelection selection) {
		return getResource(selection).getProject();
	}
	
	public static IProject getProject(IEditorInput editorInput) {
		if (editorInput instanceof FileEditorInput) {
			FileEditorInput fileEditorInput = (FileEditorInput) editorInput;

			String iproject = fileEditorInput.getPath().toString();

			String[] workspace = ResourcesPlugin.getWorkspace().getRoot()
					.getLocation().toString().split("/");
			String[] porjectStr = iproject.split("/");

			String projectName = porjectStr[workspace.length];

			IProject project = ResourcesPlugin.getWorkspace().getRoot()
					.getProject(projectName);

			return project;
		}

		return null;
	}

	public static void refreshProject(IEditorInput editorInput) {
		IProject project = getProject(editorInput);

		if (project != null) {
			try {
				project.refreshLocal(IResource.DEPTH_INFINITE, null);
			} catch (CoreException e) {
			}
		}
	}

	/**
	 * 刷新工程
	 * 
	 * @param projectName
	 */
	public static void refreshProject(String projectName) {
		if (!projectName.startsWith(File.separator)) {
			projectName = File.separator + projectName;
		}

		if (!projectName.endsWith(File.separator)) {
			projectName += File.separator;
		}

		IResource resource = findMember(ResourcesPlugin.getWorkspace()
				.getRoot(), projectName);

		if (resource != null && resource.isAccessible()) {
			try {
				resource.refreshLocal(IResource.DEPTH_INFINITE, null);
			} catch (CoreException e) {
			}
		}
	}

	private static IResource findMember(IWorkspaceRoot root, String path) {
		if (StringUtils.isNotEmpty(path)) {
			return root.findMember(new Path(path));
		}

		return null;
	}
	
	/**
	 * 判断是否是saturn构件
	 * 
	 * @param type
	 * 		      构件名字字符串
	 * @return boolean
	 * 		      是否是saturn构件
	 */
	public static boolean isSaturnCompontent(String type) {
		
		if (type.endsWith("." + SATURN_COMPONENT_ACTION) || type.endsWith("." + SATURN_COMPONENT_COMPONENT)
				|| type.endsWith(SATURN_COMPONENT_SATURNDATA) || type.endsWith("." + SATURN_COMPONENT_LOGIC)
				|| type.endsWith("." + SATURN_COMPONENT_VALIDATE) || type.endsWith(SATURN_COMPONENT_WF)
				|| type.endsWith(SATURN_COMPONENT_JSP)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获得classpath下指定资源的集合
	 * 
	 * @param project
	 * 		         saturn工程
	 * @param type
	 *        		 classpath中资源的类型
	 * @return Set<String>
	 * 				 classpath下指定资源的集合
	 */
	public static Set<String> getClassPathsByType(IProject project, String type) {
		
		Set<String> paths = new HashSet<String>();

		try {
			String projectPath = project.getLocation().toOSString();
			String tempPath = projectPath + SEPARATOR + FILECLASSPATH;
			Document document = SaturnW3CUtil.getDocument(tempPath);
			Node root = document.getDocumentElement();
			List<Node> classpathentryNodes = SaturnW3CUtil.getChildrenByName(
					root, CLASSPATH_NODE_NAME);

			if (classpathentryNodes != null) {
				for (Node classpathentryNode : classpathentryNodes) {
					String kind = SaturnW3CUtil.getNodeAttributeValue(
							classpathentryNode, CLASSPATH_ATTRIBUTE_KIND);

					if (type.equals(kind)) {
						final String path = classpathentryNode.getAttributes()
								.getNamedItem(CLASSPATH_ATTRIBUTE_PATH)
								.getNodeValue();

						paths.add(new StringBuffer(projectPath).append(
								SEPARATOR).append(path).toString());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return paths;
	}
	
	/**
	 * 判断是否是saturn构件文件夹类型
	 * 
	 * @param type
	 * 		 	   构件文件夹中的.saturn文件中的类型
	 * @return boolean
	 * 		       是否是saturn构件文件夹类型
	 */
	public static boolean isSaturnFloderType(String type) {
		
		if (SATURN_COMPONENT_ACTION.equals(type) || SATURN_COMPONENT_COMPONENT.equals(type)
				|| SATURN_COMPONENT_DATA.equals(type) || SATURN_COMPONENT_LOGIC.equals(type)
				|| SATURN_COMPONENT_VALIDATE.equals(type) || SATURN_COMPONENT_WORKFLOW.equals(type)
				|| SATURN_COMPONENT_WEB.equals(type)) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * 判断是不是指定类型的文件夹
	 * 
	 * @param path
	 *            文件夹路径
	 * @param type
	 *            要搜索文件类型
	 * @return String
	 * 			  获得指定的文件夹类型
	 */
	public static String saturnFileType(File path) {
		
		String typeValue = "";
		String typeFilePath = path.getAbsolutePath() + SEPARATOR
				+ TYPE_FILE_NAME;
		File typeFile = new File(typeFilePath);

		if (typeFile.exists()) {

			try {
				Document doc = SaturnW3CUtil.getDocument(typeFilePath.toString());
				
				if (doc != null) {
					Node root = doc.getDocumentElement();

					typeValue = SaturnW3CUtil.getChildNodeValue(root,
							SATURN_FOLDER_TYPE);
				}
			} catch (XMLException e) {
				e.printStackTrace();
			}
		}

		return typeValue;
	}
	
	/**
	 * 获取.saturn文件的中的描述信息
	 * 
	 * @param file
	 * 			  .saturn文件
	 * @return String
	 *            获得.saturn文件中的描述信息
	 */
	public static String readDescription(File file) {

		String typeFilePath = file.getAbsolutePath() + SEPARATOR
				+ TYPE_FILE_NAME;
		File typeFile = new File(typeFilePath);
		String description = "";

		if (typeFile.exists()) {
			
			try {
				Document doc = SaturnW3CUtil
						.getDocument(typeFilePath.toString());

				if (doc != null) {
					Node root = doc.getDocumentElement();
					description = SaturnW3CUtil.getChildNodeValue(root,
							SATURN_FOLDER_DESCRIPTION);
				}
			} catch (XMLException e) {
				e.printStackTrace();
			}
			
		}
		return description;
	}
}
